const cloud = require('wx-server-sdk')

cloud.init()

/// (id: RecordId) => (StatusCode)
/// StatusCode:

const SUCCESS = 0;
const BAD_PARAM = -1;
const NOT_FOUND = -2;

exports.main = async (event) => {
  const id = event.id;
  const db = cloud.database();

  if (id == null) {
    return {
      result: BAD_PARAM
    };
  }

  const record = await db.collection('records').doc(id).get();

  if (record == null) {
    return {
      result: NOT_FOUND
    };
  }

  const pooledBook = {
    book: record.book,
    time: Date.now()
  };

  await db.collection('records').doc(id).update({
    data: {
      isOpen: false
    }
  });
  await db.collection('pool').add({
    data: pooledBook
  });

  return {
    code: SUCCESS
  };
}